//
//  SentenceVC.swift
//  Game
//
//  Created by woniu on 2025/9/2.
//

import UIKit
import SnapKit
import Photos

class SentenceVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    public var gameModel:GameModel!
    public var onSubmitBlock: (()->())?
    
    private var config = SentenceConfig()
    private var nameField = UITextField()
    private let sentenceField = UITextField()
    private let blankPickerTitleLab = UILabel()
    private var wordsCollection: UICollectionView?
    private var wordsCollectionHeightConstraint: NSLayoutConstraint?
    private var words: [String] = []
    // 候选答案区域
    private let optionsTitle = UILabel()
    private var optionInputBars: [AnswerInputBar] = []
    private var correctAnswerBar:CheckBoxBar!
    private let saveButton = UIButton(type: .system)
    private var imgView:UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "添加"
        view.backgroundColor = Colors.bgColor
        if gameModel == nil{
            gameModel = GameModel.createBy(type: .sentence, name: "")
        }else{
            let dic = gameModel.jsonData.toDic()
            self.config = SentenceConfig.deserialize(from: dic) ?? SentenceConfig()
        }
        buildUI()
        
        // 返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(onBack))
        navigationController?.navigationBar.tintColor = Colors.title
        
        onRefreshWords()
    }
    
    //引用名称
    @objc func onPaste(){
        let name = nameField.text ?? ""
        sentenceField.text = name
        onRefreshWords()
    }
    
    private func buildUI() {
        
        //名称背景
        let nameCard = UIView()
        nameCard.backgroundColor = UIColor.white.withAlphaComponent(0.6)
        nameCard.layer.cornerRadius = 14
        nameCard.layer.shadowColor = UIColor.black.cgColor
        nameCard.layer.shadowOpacity = 0.06
        nameCard.layer.shadowRadius = 10
        nameCard.layer.shadowOffset = CGSize(width: 0, height: 4)
        view.addSubview(nameCard)
        nameCard.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(16)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(110)
        }
        
        let nameLab = UILabel()
        nameLab.text = "名字描述"
        nameLab.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        nameLab.textColor = Colors.title
        nameCard.addSubview(nameLab)
        nameLab.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
        }
        
        nameField.placeholder = "添加名字、描述"
        nameField.text = gameModel.name
        nameField.leftViewMode = .always
        nameField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: 40))
        nameField.rightViewMode = .always
        nameField.clearButtonMode = .unlessEditing
        nameField.textColor = .black
        nameField.circular(22)
        nameField.borderSet(Colors.blue, 2)
        nameField.font = UIFont.systemFont(ofSize: 17)
        nameCard.addSubview(nameField)
        nameField.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(8)
            make.right.equalToSuperview().offset(-90)
            make.top.equalTo(nameLab.snp.bottom).offset(10)
            make.height.equalTo(44)
        }
        
        
        imgView = UIImageView()
        if let img = GameManager.share.getImageBy(config.imageName){
            imgView.image = img
        }else{
            imgView.image = UIImage(named: "添加图片")?.withTintColor(Colors.blue)
        }
        imgView.isUserInteractionEnabled = true
        imgView.contentMode = .scaleAspectFit
        let tap = UITapGestureRecognizer(target: self, action: #selector(onTapImg(_:)))
        imgView.addGestureRecognizer(tap)
        nameCard.addSubview(imgView)
        imgView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.left.equalTo(nameField.snp.right).offset(10)
            make.height.equalTo(nameField.snp.height)
            make.top.equalTo(nameField.snp.top)
        }
        
        //==========句子背景
        let sentenceCard = UIView()
        sentenceCard.backgroundColor = UIColor.white.withAlphaComponent(0.6)
        sentenceCard.layer.cornerRadius = 14
        sentenceCard.layer.shadowColor = UIColor.black.cgColor
        sentenceCard.layer.shadowOpacity = 0.06
        sentenceCard.layer.shadowRadius = 10
        sentenceCard.layer.shadowOffset = CGSize(width: 0, height: 4)
        view.addSubview(sentenceCard)
        sentenceCard.snp.makeConstraints { make in
            make.top.equalTo(nameCard.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(110)
        }
        
        let sentenceTitleLab = UILabel()
        sentenceTitleLab.text = "完整句子"
        sentenceTitleLab.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        sentenceTitleLab.textColor = Colors.title
        sentenceCard.addSubview(sentenceTitleLab)
        sentenceTitleLab.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
        }
        
        sentenceField.placeholder = "输入完整句子"
        sentenceField.text = config.sentence
        sentenceField.borderStyle = .none
        sentenceField.backgroundColor = .clear
        sentenceField.circular(22)
        sentenceField.borderSet(Colors.blue, 2)
        sentenceField.clearButtonMode = .whileEditing
        sentenceField.delegate = self
        let pad = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 44))
        sentenceField.leftView = pad
        sentenceField.leftViewMode = .always
        sentenceCard.addSubview(sentenceField)
        sentenceField.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(8)
            make.right.equalToSuperview().offset(-90)
            make.top.equalTo(sentenceTitleLab.snp.bottom).offset(10)
            make.height.equalTo(44)
        }
        
        let pasteButton = UIButton(type: .system)
        pasteButton.setImage(UIImage(systemName: "arrowshape.turn.up.left.2"), for: .normal)
        pasteButton.tintColor = Colors.blue
        pasteButton.imageView?.contentMode = .scaleAspectFit
        pasteButton.addTarget(self, action: #selector(onPaste), for: .touchUpInside)
        sentenceCard.addSubview(pasteButton)
        pasteButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.left.equalTo(sentenceField.snp.right).offset(10)
            make.height.equalTo(sentenceField.snp.height)
            make.top.equalTo(sentenceField.snp.top)
        }
        
        //========== 镂空容器卡片
        let blankContainer = UIView()
        blankContainer.backgroundColor = UIColor.white.withAlphaComponent(0.6)
        blankContainer.layer.cornerRadius = 14
        blankContainer.layer.shadowColor = UIColor.black.cgColor
        blankContainer.layer.shadowOpacity = 0.06
        blankContainer.layer.shadowRadius = 10
        blankContainer.layer.shadowOffset = CGSize(width: 0, height: 4)
        view.addSubview(blankContainer)
        blankContainer.snp.makeConstraints { make in
            make.top.equalTo(sentenceCard.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            // 高度改为自适应，底部在稍后绑定到 collectionView
        }
        blankPickerTitleLab.text = "选择镂空单词"
        blankPickerTitleLab.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        blankPickerTitleLab.textColor = Colors.title
        blankContainer.addSubview(blankPickerTitleLab)
        blankPickerTitleLab.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
        }
        
        // 单词 chips 列表
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 12
        layout.minimumLineSpacing = 12
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.register(WordChipCell.self, forCellWithReuseIdentifier: WordChipCell.reuseId)
        collectionView.dataSource = self
        collectionView.delegate = self
        blankContainer.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(blankPickerTitleLab.snp.bottom).offset(12)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
        }
        // 让 blankContainer 的底部跟随 collectionView 的底部（加一点内边距）
        blankContainer.snp.remakeConstraints { make in
            make.top.equalTo(sentenceCard.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalTo(collectionView.snp.bottom).offset(12)
        }
        // 初始高度，后续在 onRefreshWords 更新
        wordsCollectionHeightConstraint = collectionView.heightAnchor.constraint(equalToConstant: 120)
        wordsCollectionHeightConstraint?.isActive = true
        self.wordsCollection = collectionView
        
        //============答案列表容器卡片
        let optionsCard = UIView()
        optionsCard.backgroundColor = UIColor.white.withAlphaComponent(0.6)
        optionsCard.layer.cornerRadius = 14
        optionsCard.layer.shadowColor = UIColor.black.cgColor
        optionsCard.layer.shadowOpacity = 0.06
        optionsCard.layer.shadowRadius = 10
        optionsCard.layer.shadowOffset = CGSize(width: 0, height: 4)
        view.addSubview(optionsCard)
        optionsCard.snp.makeConstraints { make in
            make.top.equalTo(blankContainer.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(140)
        }
        
        // 标题
        optionsTitle.text = "候选答案"
        optionsTitle.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        optionsTitle.textColor = Colors.title
        optionsCard.addSubview(optionsTitle)
        optionsTitle.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
        }
        
        func makeCardField(_ index:Int,_ title:String,_ isShowDelete:Bool) -> AnswerInputBar {
            let bar = AnswerInputBar(frame: .zero)
            bar.inputField.delegate = self
            bar.tag = index
            bar.onDidChangeBlock = {[weak self]in
                guard let `self` = self else { return }
                self.refreshCorrectView()
            }
            bar.onDidEditFinishBlock = {[weak self]in
                guard let `self` = self else { return }
                self.refreshCorrectView()
            }
            bar.deleteButton.isHidden = !isShowDelete
            bar.indexLab.text = title
            bar.circular(30)
            optionsCard.addSubview(bar)
            return bar
        }
        
        let bar1 = makeCardField(0,"A",false)
        let bar2 = makeCardField(1,"B",false)
        let bar3 = makeCardField(2,"C",false)
        let bar4 = makeCardField(3,"D",true)
        let optionsCount = config.options.count
        
        if optionsCount >= 1{
            bar1.inputField.text = config.options[0]
        }
        if optionsCount >= 2{
            bar2.inputField.text = config.options[1]
        }
        if optionsCount >= 3{
            bar3.inputField.text = config.options[2]
        }
        if optionsCount >= 4{
            bar4.inputField.text = config.options[3]
        }
        bar1.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(40)
            make.width.equalToSuperview().multipliedBy(0.2)
            make.height.equalTo(60)
        }
        bar2.snp.makeConstraints { make in
            make.left.equalTo(bar1.snp.right).offset(15)
            make.top.equalTo(bar1.snp.top)
            make.size.equalTo(bar1.snp.size)
        }
        bar3.snp.makeConstraints { make in
            make.left.equalTo(bar2.snp.right).offset(15)
            make.top.equalTo(bar1.snp.top)
            make.size.equalTo(bar1.snp.size)
        }
        bar4.snp.makeConstraints { make in
            make.left.equalTo(bar3.snp.right).offset(15)
            make.top.equalTo(bar1.snp.top)
            make.size.equalTo(bar1.snp.size)
        }
        optionInputBars =  [bar1, bar2, bar3, bar4]
        
        //======答案卡片
        let answerCard = UIView()
        answerCard.backgroundColor = UIColor.white.withAlphaComponent(0.6)
        answerCard.layer.cornerRadius = 14
        answerCard.layer.shadowColor = UIColor.black.cgColor
        answerCard.layer.shadowOpacity = 0.06
        answerCard.layer.shadowRadius = 10
        answerCard.layer.shadowOffset = CGSize(width: 0, height: 4)
        view.addSubview(answerCard)
        answerCard.snp.makeConstraints { make in
            make.top.equalTo(optionsCard.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(140)
        }
        
        let answerTitleLab = UILabel()
        answerTitleLab.text = "选择正确的答案"
        answerTitleLab.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        answerTitleLab.textColor = Colors.title
        answerCard.addSubview(answerTitleLab)
        answerTitleLab.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
        }
        
        correctAnswerBar = CheckBoxBar(frame: .zero)
        answerCard.addSubview(correctAnswerBar)
        correctAnswerBar.snp.makeConstraints { make in
            make.top.equalTo(answerTitleLab.snp.bottom).offset(10)
            make.left.right.equalTo(sentenceField)
            make.bottom.equalToSuperview().offset(-10)
        }
        refreshCorrectView()
        
        saveButton.setTitle("保存", for: .normal)
        saveButton.backgroundColor = Colors.buttonBlue
        saveButton.setTitleColor(.white, for: .normal)
        saveButton.layer.cornerRadius = 22
        saveButton.layer.shadowColor = UIColor.black.cgColor
        saveButton.layer.shadowOpacity = 0.12
        saveButton.layer.shadowRadius = 6
        saveButton.layer.shadowOffset = CGSize(width: 0, height: 3)
        view.addSubview(saveButton)
        
        saveButton.addTarget(self, action: #selector(onSave), for: .touchUpInside)
        saveButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-16)
            make.height.equalTo(44)
            make.width.equalTo(220)
        }
    }
    
    @objc func onTapImg(_ deco:UITapGestureRecognizer){
        if !config.imageName.isEmpty,let img = GameManager.share.getImageBy(config.imageName){
            let sheet = UIAlertController(
                title: "请选择",
                message: nil,
                preferredStyle: .actionSheet
            )
            
            sheet.addAction(UIAlertAction(title: "查看大图", style: .default) {_ in
                PhotoBrowserService().show(0, [img])
            })
            sheet.addAction(UIAlertAction(title: "删除", style: .default) {[weak self] _ in
                guard let `self` = self else { return }
                GameManager.share.delete(imgNames: [self.config.imageName])
                self.config.imageName = ""
                self.imgView.image = UIImage(named: "添加图片")?.withTintColor(Colors.blue)
            })
            sheet.addAction(UIAlertAction(title: "取消", style: .cancel){_ in
            })
            // iPad: actionSheet 必须设置 popoverPresentationController 的锚点，否则会崩溃
            if let pop = sheet.popoverPresentationController {
                pop.sourceView = self.imgView
                pop.sourceRect = .zero
                pop.permittedArrowDirections = .any
            }
            MyNavigator.getTopVC()?.present(sheet, animated: true)
        }else{
            self.selectImageFromAlbum()
        }
    }
    
    // MARK: - Chips DataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return words.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WordChipCell.reuseId, for: indexPath) as! WordChipCell
        let w = words[indexPath.item]
        // 彩色轮换
        // 使用更柔和的配色（系统色 + 降低透明度在 cell 内处理）
        let palette: [UIColor] = [
            UIColor.systemPink,
            UIColor.systemBlue,
            UIColor.systemGreen,
            UIColor.systemYellow,
            UIColor.systemPurple
        ]
        let color = palette[indexPath.item % palette.count]
        cell.configure(text: w, color: color, selected: w == config.blankWord)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        config.blankWord = words[indexPath.item]
        collectionView.reloadData()
    }
    
    // 自动根据内容宽度布局
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = words[indexPath.item]
        // 与 WordChipCell 中的字体和内边距一致：左右各18，合计36
        let font = UIFont.systemFont(ofSize: 20, weight: .bold)
        let width = ceil((text as NSString).size(withAttributes: [.font: font]).width) + 40
        return CGSize(width: max(60, width), height: 48)
    }
    
    @objc private func onBack() {
        if let nav = navigationController {
            nav.popViewController(animated: true)
        } else {
            dismiss(animated: true)
        }
    }
    
    //
    @objc private func onRefreshWords() {
        words = sentenceField.text?.split(separator: " ").map(String.init) ?? []
        wordsCollection?.reloadData()
        // 延迟一帧以便 collectionView 更新 contentSize
        DispatchQueue.main.async {
            guard let cv = self.wordsCollection, let hConstraint = self.wordsCollectionHeightConstraint else { return }
            cv.layoutIfNeeded()
            // 计算合适高度（最多三行，最小一行）
            let contentHeight = cv.collectionViewLayout.collectionViewContentSize.height
            let minH: CGFloat = 48
            let maxH: CGFloat = 240
            let targetH = min(max(contentHeight, minH), maxH)
            if hConstraint.constant != targetH {
                UIView.animate(withDuration: 0.25) {
                    hConstraint.constant = targetH
                    self.view.layoutIfNeeded()
                }
            }
        }
    }
    
    //刷新答案列表
    public func refreshCorrectView(){
        var titles:[String] = []
        for bar in optionInputBars{
            if bar.isHiddenItem == false{
                let text = (bar.inputField.text ?? "").replaceRN()
                if !text.isEmpty{
                    titles.append(text)
                }
                
            }
        }
        correctAnswerBar.clear()
        correctAnswerBar.setOptions(titles)
        correctAnswerBar.updateSlected(by: config.correctAnswer)
    }
    
    @objc private func onSave() {
        //句子
        config.sentence = sentenceField.text ?? ""
        //选项
        config.options = optionInputBars.compactMap { $0.inputField.text?.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.replaceRN().isEmpty }
        //正确答案
        //名称
        gameModel.name = nameField.text ?? ""
        
        if gameModel.name.isEmpty{
            ToastView.show("请输入名称、描述")
            return
        }
        if config.sentence.isEmpty{
            ToastView.show("请输入句子")
            return
        }
        if config.blankWord.isEmpty{
            ToastView.show("请选择镂空单词")
            return
        }
        if config.options.isEmpty{
            ToastView.show("请输入选项")
            return
        }
        //正确答案
        let itemObj  = correctAnswerBar.getSelectedItem()
        config.correctAnswer = itemObj?.val ?? ""
        if config.correctAnswer.isEmpty{
            ToastView.show("请输入正确答案")
            return
        }
        if let json = config.toJSONString() {
            print(json)
            gameModel.jsonData = json
            GameManager.share.insertOrUpdate(game: gameModel)
            onSubmitBlock?()
            self.onBack()
        } else {
            print("JSON 序列化失败")
        }
    }
    
}

//当句子输入完成，刷新需要镂空的模块
extension SentenceVC:UITextFieldDelegate{
    
    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
        onRefreshWords()
        refreshCorrectView()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        onRefreshWords()
        refreshCorrectView()
        return true
    }
}

extension SentenceVC{
    // 触发选择图片的方法（例如按钮点击）
    func selectImageFromAlbum() {
        // 检查相册访问权限
        checkPhotoLibraryPermission { [weak self] granted in
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                guard granted else {
                    self.showPermissionAlert()
                    return
                }
                let imagePicker = UIImagePickerController()
                imagePicker.sourceType = .photoLibrary
                imagePicker.allowsEditing = true
                imagePicker.delegate = self
                MyNavigator.getTopVC()?.present(imagePicker, animated: true, completion: nil)
            }
        }
    }
    
    // 检查相册权限
    private func checkPhotoLibraryPermission(completion: @escaping (Bool) -> Void) {
        switch PHPhotoLibrary.authorizationStatus(for: .readWrite) {
        case .authorized:
            completion(true)
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
                completion(status == .authorized)
            }
        case .denied, .restricted:
            completion(false)
        case .limited:
            completion(true)
        @unknown default:
            completion(false)
        }
    }
    
    // 显示权限不足提示
    private func showPermissionAlert() {
        let alert = UIAlertController(
            title: "无法访问相册",
            message: "请在设置中允许应用访问您的相册",
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        alert.addAction(UIAlertAction(title: "设置", style: .default) { _ in
            guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { return }
            UIApplication.shared.open(settingsURL)
        })
        MyNavigator.getTopVC()?.present(alert, animated: true)
    }
    
}

extension SentenceVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    // 图片选择完成回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let selectedImage = info[.editedImage] as? UIImage,let data = selectedImage.pngData(){
            self.imgView.image = selectedImage
            self.config.imageName = "img_\(self.gameModel.key)_sentence_\(DateUtil.currentDate(format: "mmss"))"
            GameManager.share.saveOrReplace(name:config.imageName, image: data)
        }
        picker.dismiss(animated: true, completion: nil)
    }
}
